const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 1009;

// 启用CORS
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static('uploads'));

// 数据文件路径
const DATA_FILE = path.join(__dirname, 'data.json');

// 初始化记录数据和上传目录
let records = [];
const uploadDir = path.join(__dirname, 'uploads');

// 确保上传目录存在
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// 从文件加载数据
function loadRecords() {
    try {
        if (fs.existsSync(DATA_FILE)) {
            const data = fs.readFileSync(DATA_FILE, 'utf8');
            records = JSON.parse(data);
            console.log('从 data.json 加载记录成功');
        }
    } catch (err) {
        console.error('加载记录文件时出错:', err);
    }
}

// 保存数据到文件（按天替换模式）
function saveRecords() {
    try {
        // 读取现有文件内容（如果存在）
        let existingData = [];
        if (fs.existsSync(DATA_FILE)) {
            const fileContent = fs.readFileSync(DATA_FILE, 'utf8');
            existingData = JSON.parse(fileContent);
        }

        // 合并/替换记录
        records.forEach(newRecord => {
            const existingIndex = existingData.findIndex(r => r.day === newRecord.day);
            if (existingIndex >= 0) {
                // 替换当天记录
                existingData[existingIndex] = newRecord;
            } else {
                // 添加新记录
                existingData.push(newRecord);
            }
        });

        // 按day排序
        existingData.sort((a, b) => a.day - b.day);

        // 写入文件（完全覆盖）
        fs.writeFileSync(DATA_FILE, JSON.stringify(existingData, null, 2));
        console.log('记录已保存到 data.json');
    } catch (err) {
        console.error('保存记录文件时出错:', err);
    }
}

// 启动时加载数据
loadRecords();

// 配置multer用于文件上传
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
        const today = new Date();
        const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
        cb(null, 'day-' + dateStr + path.extname(file.originalname));
    }
});

const upload = multer({ storage: storage });

// 上传照片接口
app.post('/api/upload', upload.single('photo'), (req, res) => {
    if (!req.file) {
        return res.status(400).json({ error: '没有上传文件' });
    }

    const photoUrl = `/uploads/${req.file.filename}`;
    res.json({ photoUrl });
    console.log('===>photoUrl', photoUrl);
});

// 保存记录接口
app.post('/api/records', (req, res) => {
    const { day, date, photoUrl, note } = req.body;

    // 验证数据
    if (!day || !date) {
        return res.status(400).json({ error: '缺少必要字段' });
    }

    // 查找并更新记录
    const existingIndex = records.findIndex(r => r.day === parseInt(day));
    const newRecord = {
        day: parseInt(day),
        date,
        photoUrl: photoUrl || null,
        note: note || ''
    };

    if (existingIndex >= 0) {
        records[existingIndex] = newRecord;
    } else {
        records.push(newRecord);
    }

    // 保存并返回
    saveRecords();
    res.json({ success: true, record: newRecord });
});

// 获取所有记录
app.get('/api/records', (req, res) => {
    loadRecords()
    res.json(records);
});

// 添加根路由处理
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});

// 启动时加载数据
function initializeData() {
    try {
        if (fs.existsSync(DATA_FILE)) {
            const data = fs.readFileSync(DATA_FILE, 'utf8');
            records = JSON.parse(data);
            console.log(`从 ${DATA_FILE} 加载了 ${records.length} 条记录`);
        } else {
            records = [];
            console.log('未找到数据文件，将创建新文件');
        }
    } catch (err) {
        console.error('初始化数据时出错:', err);
        records = [];
    }
}

// 服务器启动时调用
initializeData();
